package cn.jee.controller;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@Controller
public class FileController {
  @RequestMapping("/file_input")
  public String input(String id, Model model){
    model.addAttribute("id",id);
    return "file_input";
  }
  @Value("${file.save.path}")
  String savePath;
  @RequestMapping("/file_upload")
  public String upload(MultipartFile file, RedirectAttributes redirectAttributes) throws IOException {
    if(file.isEmpty()){
      redirectAttributes.addFlashAttribute("msg","没有选择文件");
      return "redirect:/file_input";
    }
    System.out.println(file.getContentType());
    System.out.println(file.getOriginalFilename());
    File destFile=new File(savePath,file.getOriginalFilename());
    file.transferTo(destFile);

    redirectAttributes.addAttribute("fileName",file.getOriginalFilename());
    redirectAttributes.addAttribute("contentType",file.getContentType());

    return "redirect:/upload_res";
  }
  @RequestMapping("/upload_res")
  public String uploadRes(){
    return "upload_res";
  }
  @RequestMapping("/file_down")
  public void down(String fileName, String contentType, HttpServletResponse response) throws IOException {
    Path path= Paths.get(savePath,fileName);
    response.setContentType(contentType);
    response.addHeader(HttpHeaders.CONTENT_DISPOSITION,"attachment; filename="+toCn(fileName));
    Files.copy(path,response.getOutputStream());
  }
  private String toCn(String fileName){
    return new String(fileName.getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1);
  }
  @RequestMapping("/files_upload")
  public String uploads(List<MultipartFile> files,RedirectAttributes redirectAttributes){
    boolean isEmpty=files.stream().allMatch(MultipartFile::isEmpty);
    if(isEmpty){
      redirectAttributes.addFlashAttribute("msg","必须至少选择一个文件");
      return "redirect:/file_input";
    }
    return "upload_res";
  }
}
